package com.firefly.mobile.app.context;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Log;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.location.Poi;
import com.firefly.app.biz.yhc.dto.UserLoginRequest;
import com.firefly.app.biz.yhc.service.YHCService;
import com.firefly.app.biz.yhc.service.YHCServiceImpl;
import com.firefly.mobile.app.context.init.BizPackInitFactory;
import com.firefly.mobile.app.context.init.ConfigInitFactory;
import com.firefly.mobile.app.main.FireflyMobileActivity;
import com.firefly.mobile.app.util.SytLog;
import com.firefly.mobile.app.util.context.ConfInitFactory;
import com.umeng.socialize.PlatformConfig;
//假如用到位置提醒功能，需要import该类
import com.umeng.socialize.UMShareAPI;

@SuppressLint("NewApi")
public class SytApplication  extends Application{
	
	//默认环境配置 dev or prd 
	public static String env = "dev";
	public static final String DEV = "dev";
	public static final String PRD = "prd";
	
	
	public static Context context;
	// -------------------------SDK配置文件-------------
	public static final String PACK_FOLDER_ROOT = "conf";
	public static final String LOCAL_FOLDER_ROOT = "localdata";
	public static final String WWW_FOLDER_ROOT = "www";

	// -------------------------SDK业务配置-------------
	public static final String TRANS_PACK_FOLDER_PATH = PACK_FOLDER_ROOT + "/pack/trans";
	public static final String BIZ_PACK_FOLDER_PATH = PACK_FOLDER_ROOT + "/pack/biz";
	public static final String CONFIG_FILE_PATH = PACK_FOLDER_ROOT + "/config.xml";
	// ---------------------------------------------------------------

//	public static boolean initResult = false;//由于采用异步处理，需要增加标志位。防止获取配置信息为空值
    
    //----------------地图定位相关
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();
    public static double lat = 0;
    public static double lon = 0;
    public static  String cityCode = "289";
    public static  String loCity = "";
    public static  String loProvince = "";
    public static  String district = "";
    
	//以下是小米推送代码
	public static final String APP_ID = "2882303761517472919";
    public static final String APP_KEY = "5701747216919";
    public static final String TAG = "com.firefly.mobile.app";
    
	@Override
	public void onCreate() {
		super.onCreate();
		
//		mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
//	    mLocationClient.registerLocationListener( myListener );    //注册监听函数
//	    initLocation();
//	    mLocationClient.start();
	    
		context = this;
		try {
			context=getApplicationContext();
            Log.i(TAG, "阿里云推送注册开始");

			//初始化push推送服务
			initCloudChannel(this);
		
			MyAsyncTask myAsyncTask = new MyAsyncTask();
			myAsyncTask.execute(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
        //友盟 社会化 分享
        PlatformConfig.setWeixin("wx0bf7c52958ebc15d", "aa25cf3a83d2261a961f0e6f07aa3498");
        PlatformConfig.setQQZone("1105922581", "IlrOMw1uOKXPdL0K");
        
        //新浪微博 appkey appsecret
//        PlatformConfig.setSinaWeibo("4211410923","5fbd4e95ad2cdb5621998722efbd7f38");



        UMShareAPI.get(this);
        
        //字体补丁
    	Resources resource = getResources();
    	Configuration configuration =resource.getConfiguration();
    	configuration .fontScale = 1.0f;//设置字体的缩放比例
    	resource.updateConfiguration(configuration , resource.getDisplayMetrics());

		    
	}
	
	
	/**
	 * 初始化阿里云推送通道
	 * @param applicationContext
	 */
	private void initCloudChannel(Context applicationContext) {
	    PushServiceFactory.init(applicationContext);
	    CloudPushService pushService = PushServiceFactory.getCloudPushService();
	    pushService.register(applicationContext, new CommonCallback() {
	        @Override
	        public void onSuccess(String response) {
	            Log.i(TAG, "阿里云推送注册成功，init cloudchannel success");
	        }
	        @Override
	        public void onFailed(String errorCode, String errorMessage) {
	            Log.i(TAG, "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
	        }
	    });
	}
	
	public static UserLoginRequest ReadSharedPreferences(){
		UserLoginRequest userLoginRequest = new UserLoginRequest();
		try {
			String strName,strPassword;
			SharedPreferences   user = context.getSharedPreferences("user_info",0);
			strName = user.getString("mobileNo","");
			strPassword = user.getString("password","");
			
			userLoginRequest.setMobileNo(strName);
			userLoginRequest.setPassword(strPassword);
			SytLog.i("从缓存中读出用户信息"+strName+strPassword);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return userLoginRequest;
		
	}
	public static void WriteSharedPreferences(String strName,String strPassword){
		SharedPreferences user = context.getSharedPreferences("user_info",0);
		Editor editor= user.edit();
		editor.putString("mobileNo", strName);
		editor.putString("password" ,strPassword);
		editor.commit();
		SytLog.i("写入用户信息"+strName+strPassword);
	}
	
	
	
	class MyAsyncTask extends AsyncTask<Context,Integer,Integer>{
		
		@Override
		protected void onPreExecute() {
			if (android.os.Build.VERSION.SDK_INT > 9) {
				StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
				StrictMode.setThreadPolicy(policy);
			}
		}

		@Override
		protected Integer doInBackground(Context... params) {
			try {
				Context context = params[0];
				
				ConfInitFactory init = new ConfInitFactory(){
					@Override
					public int initConf(Context context) {
							//开始加载配置文件
							try {
								new ConfigInitFactory().init(context);
								new BizPackInitFactory().init(context);
							} catch (Exception e) {
								e.printStackTrace();
							}
							Log.i("SytPackApplication","初始化配置文件成功");
							
							Log.i( "SytPackApplication", "配置文件初始完毕");

					        YHCService yhcService = new YHCServiceImpl();
							yhcService.autoLogin();
							
							return 0;
					}

					@Override
					public int copyAssert(Context context) {
						return 0;
					}
					
				};
				//初始化配置信息
				init.initConf(context);
			} catch (Exception e) {
				e.printStackTrace();
				Log.i("SytPackApplication",  e.toString());
			}
			return 0;
		}
	}


	public static Context getContext() {
		return context;
	}
	
	
	public static void setContext(Context context) {
		SytApplication.context = context;
	}

	/**
	 * dev：从apk中读取文件 
	 * prd：从sdcard中读取文件
	 * 根据环境变量 获取配置文件路径
	 * 
	 * 目前配置文件是从sdcard中读取
	 * @return 路径
	 */
	public static String getSdcardFilePath(){
		return Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+context.getPackageName();
	}

	
	
	/**
	 * dev：从apk中读取文件 
	 * prd：从sdcard中读取文件
	 * 根据环境变量 获取配置文件路径
	 * 
	 * 目前配置文件是从sdcard中读取
	 * @return 路径
	 */
	public static InputStream  getFileInputStreamByEnv(String fileName){
		InputStream inputStream = null;
		try {
			if (DEV.equals(env)) {
				
				inputStream = context.getResources().getAssets().open(fileName);
				
			}else if (PRD.equals(env)) {
				
				inputStream = new FileInputStream(new File(Environment
						.getExternalStorageDirectory().getAbsolutePath()
						+ File.separator + context.getPackageName()
						+ File.separator + fileName));

			}
		
		} catch (IOException e) {
			e.printStackTrace();
		}
		return inputStream;
	}
	
	
	/**
	 * @return 
	 */
	public static String[]  getFileListByEnv(String fileName){
		String[] list = null;
		try {
			if (DEV.equals(env)) {
				
				list = context.getResources().getAssets().list(fileName);
				
			}else if (PRD.equals(env)) {
				
				list = new File(Environment.getExternalStorageDirectory()
						.getAbsolutePath()
						+ File.separator
						+ context.getPackageName()
						+ File.separator + fileName).list();

			}
		
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}
	
	
	private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span=1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于"在北京天安门附近"
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到option.setIgnoreKillProcess(false);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }
	
	
	
	
	
//	private void testSend() throws RemoteException{
//		AnAnPackSocket anAnPackSocket = new AnAnPackSocket();
//		MobileReq<MobileDTO> reqObj = new MobileReq<MobileDTO>();
//		MobileDTO mobileDTO = new MobileDTO();
//		mobileDTO.setMobileNo("18701948710");
//		mobileDTO.setBizAmt("100");
//		reqObj.setBizType("mobilerecharge");
//		reqObj.setContent(mobileDTO);
//		
//		String reqParams = new JsonConvertUtils<MobileReq<MobileDTO>>().obj2Json(reqObj);
//		SytLog.i("开始调用服务,reqParams=>"+reqParams);
//		anAnPackSocket.send(reqParams);
//	}
    /**
     * 获取版本号
     * @return 当前应用的版本号
     */
    public static String getVersion() {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            Log.e("获取版本号", version);
            return version;
        } catch (Exception e) {
        	Log.e("获取版本号", "错误",e);
            e.printStackTrace();
            return "";
        }
    }
    
    public class MyLocationListener implements BDLocationListener {
    	 
        @Override
        public void onReceiveLocation(BDLocation location) {
        	boolean locatSuccess = false;
            //Receive Location
            StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            if (location.getLocType() == BDLocation.TypeGpsLocation){// GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());// 单位：公里每小时
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\nheight : ");
                sb.append(location.getAltitude());// 单位：米
                sb.append("\ndirection : ");
                sb.append(location.getDirection());// 单位度
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");
                locatSuccess = true;
 
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){// 网络定位结果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                //运营商信息
                sb.append("\noperationers : ");
                sb.append(location.getOperators());
                sb.append("\ndescribe : ");
                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
            	sb.append("\n城市信息 : "+location.getCity()+"cityCode:"+location.getCityCode());
            	sb.append("\nlocationdescribe : ");
                sb.append(location.getLocationDescribe());// 位置语义化信息
                List<Poi> list = location.getPoiList();// POI数据
                if (list != null) {
                    sb.append("\npoilist size = : ");
                    sb.append(list.size());
                    for (Poi p : list) {
                        sb.append("\npoi= : ");
                        sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                    }
                }
            Log.i("BaiduLocationApiDem", sb.toString());
            
            lat = location.getLatitude();
            lon = location.getLongitude();
//            cityCode = location.getCityCode();
           
            
            if (lat != 0 && lon != 0) {
            	SytApplication.cityCode = location.getCityCode();
            	SytApplication.loCity = location.getCity();
            	SytApplication.loProvince = location.getProvince();
            	SytApplication.district = location.getDistrict();
            	  Log.i("BaiduLocationApiDem","区县信息"+location.getDistrict());
            	Timer timer = new Timer();
        		timer.schedule(new TimerTask() {
        			@Override
        			public void run() {
        				try {
        					FireflyMobileActivity.sendMsgToSytActivity("jsExec|setLocationCityInfo("+lat+","+lon+",'"+cityCode+"','"+loProvince+"','"+loCity+"','"+district+"')");
        				} catch (Exception e) {
        					e.printStackTrace();
        				}
        			}
        	    	  //3秒delay
        	      }, 3*1000); 
        		
            	
            	if (locatSuccess || (location.getCityCode() != null && !location.getCityCode().equals(""))) {
            		Log.i("BaiduLocationApiDem","定位成功，关闭gps定位");
            		mLocationClient.stop();                	
    			}
			}
            mLocationClient.stop();
        }
    }
}
